import {mutationWithClientMutationId, cursorForObjectInConnection, fromGlobalId} from "graphql-relay";
import {GraphQLInt, GraphQLBoolean, GraphQLString, GraphQLID} from "graphql";
import {connectionFromType} from "../../connection";
import SsidType from "../../types/SsidType";
import { Profile, Ssid } from '../../models';
import ProfileType from "../../types/ProfileType";

const AddSsidMutation = mutationWithClientMutationId({
  name: 'addSsid',
  inputFields: {
    profile_id: { type: GraphQLID },
    name: { type: GraphQLString },
    auth: { type: GraphQLString },
    cipher: {type: GraphQLString },
    pwd: { type: GraphQLString },
    ishide: { type: GraphQLBoolean },
    category: { type: GraphQLInt },
  },
  outputFields: {
    ssidEdge: {
      type: connectionFromType('ssid', SsidType).edge,
      resolve: async ({ profileId, ssidId }) => {
        const ssids = await Ssid.findAll({where: {
          profile_id: profileId
        }});
        const ssid = ssids.find(o => o.get('id') === ssidId);
        return {
          cursor: cursorForObjectInConnection(ssids, ssid),
          node: ssid,
        };
      },
    },
    profile: {
      type: ProfileType,
      resolve: ({profileId}) => Profile.findById(profileId),
    },
  },
  mutateAndGetPayload: async({profile_id, name, auth, cipher, pwd, ishide, category}) => {
    const profileId = parseInt(fromGlobalId(profile_id).id, 10);
    const ssid = await Ssid.create({profile_id: profileId, name, auth, cipher, pwd, ishide, category});
    const ssidId = ssid.dataValues.id;
    return { ssidId, profileId };
  },
});

export default AddSsidMutation;
